package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 测试分布式锁
     * @param id
     * @return
     */
//    @Override
//    @Cacheable(cacheNames = "ca", key = "#id", sync = true)
//    public CategoryEntity findById(Long id) {
//        RLock lock = redissonClient.getLock("redissonClient-lock");
//
//        lock.lock();
//        CategoryEntity ca = new CategoryEntity();
//        try {
//            System.out.println("数据库");
//            ca = baseMapper.selectById(id);
//            Thread.sleep(15000);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            lock.unlock();
//        }
//        return ca;
//    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> list = list(null);
        List<CategoryEntity> categoryList = new ArrayList<>();
        Map<Long, List<CategoryEntity>> categoryMap = list.stream().map(item -> {
            CategoryEntity categoryEntity = new CategoryEntity();
            BeanUtils.copyProperties(item, categoryEntity);
            return categoryEntity;
        }).collect(Collectors.groupingBy(CategoryEntity::getParentCid, Collectors.toList()));


        categoryMap.forEach((key,value)->{
            if (key == 0) {
                categoryList.addAll(value);
            }
            value.forEach(item->{
                item.setChildren(categoryMap.get(item.getCatId()));
            });
        });

        return categoryList;
    }

    // 批量删除
    @Override
    public void removeMenuByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    @Transactional
    @CacheEvict(value = "category", key = "'getLevel1Categorys'")
    public void updateDetail(CategoryEntity category) {
        baseMapper.updateById(category);
        if (!category.getName().isEmpty()) {
            categoryBrandRelationService.updateCategory(category);
        }
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    @Cacheable(value = {"category"}, key = "#root.method.name")
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = "category", key = "#root.methodName",sync = true)
    @Override
    public Map<String,List<Catelog2Vo>> getCatalogJson(){
        System.out.println("查询了数据库");
        /**************************** 耗时10-20ms ****************************/
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        // 所有一级分类
        List<CategoryEntity> category1Data = categoryEntityList.stream()
                .filter(item -> item.getParentCid() == 0)
                .collect(Collectors.toList());

        Map<String, List<Catelog2Vo>> data = category1Data.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<Catelog2Vo> catelog2Vos = categoryEntityList.stream()
                    .filter(f2 -> f2.getParentCid() == v.getCatId())
                    .map(lv2 -> {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = categoryEntityList.stream()
                                .filter(f3 -> f3.getParentCid() == lv2.getCatId())
                                .map(lv3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                                    catelog3Vo.setCatelog2Id(lv3.getParentCid().toString());
                                    catelog3Vo.setName(lv3.getName());
                                    catelog3Vo.setId(lv3.getCatId().toString());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                        Catelog2Vo catelog2Vo = new Catelog2Vo();
                        catelog2Vo.setCatelog1Id(lv2.getParentCid().toString());
                        catelog2Vo.setName(lv2.getName());
                        catelog2Vo.setId(lv2.getCatId().toString());
                        catelog2Vo.setCatelog3List(catelog3Vos);
                        return catelog2Vo;
                    }).collect(Collectors.toList());
            return catelog2Vos;
        }));
        return data;
    }

    @Override
    public Map<String,List<Catelog2Vo>> getCatalogJson2() throws InterruptedException {
        String catalogJson = (String) redisTemplate.opsForValue().get("catalogJson");
        if (catalogJson == null) {
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
            return catalogJsonFromDb;
        }
        System.out.println("查询了缓存");
        Map<String, List<Catelog2Vo>> map = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return map;
    }

    /**
     * 分布式锁
     * @return
     */
    public Map<String,List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() throws InterruptedException {
        RLock lock = redissonClient.getLock("my-lock");
        Map<String, List<Catelog2Vo>> dataFromDb = null;
        lock.lock(30,TimeUnit.SECONDS);
        try {
            dataFromDb = getDataFromDb();
//            Thread.sleep(30000);
        } finally {
            lock.unlock();
        }
        return dataFromDb;
//        String uuid = UUID.randomUUID().toString();
//        // 保证加锁的原子性
//        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,30, TimeUnit.SECONDS);
//        if (lock) {
//            System.out.println("获取分布式锁成功");
//            // 加锁成功
//            Map<String, List<Catelog2Vo>> dataFromDb;
//            try {
//                dataFromDb  = getDataFromDb();
//            } finally {
//                // 删除锁，需要保证删锁的原子性，所以使用lua脚本
//                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
//            }
//            return dataFromDb;
//        } else {
//            System.out.println("获取分布式锁失败。。。。。。");
//            Thread.sleep(200);
//            // 加锁失败
//            return getCatalogJsonFromDbWithRedisLock();
//        }
    }

    // 获取三级分类
    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJson = (String) redisTemplate.opsForValue().get("catalogJson");
        if (catalogJson != null) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        System.out.println("查询了数据库");
        /**************************** 耗时10-20ms ****************************/
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        // 所有一级分类
        List<CategoryEntity> category1Data = categoryEntityList.stream()
                .filter(item -> item.getParentCid() == 0)
                .collect(Collectors.toList());

        Map<String, List<Catelog2Vo>> data = category1Data.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<Catelog2Vo> catelog2Vos = categoryEntityList.stream()
                    .filter(f2 -> f2.getParentCid() == v.getCatId())
                    .map(lv2 -> {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = categoryEntityList.stream()
                                .filter(f3 -> f3.getParentCid() == lv2.getCatId())
                                .map(lv3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                                    catelog3Vo.setCatelog2Id(lv3.getParentCid().toString());
                                    catelog3Vo.setName(lv3.getName());
                                    catelog3Vo.setId(lv3.getCatId().toString());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                        Catelog2Vo catelog2Vo = new Catelog2Vo();
                        catelog2Vo.setCatelog1Id(lv2.getParentCid().toString());
                        catelog2Vo.setName(lv2.getName());
                        catelog2Vo.setId(lv2.getCatId().toString());
                        catelog2Vo.setCatelog3List(catelog3Vos);
                        return catelog2Vo;
                    }).collect(Collectors.toList());
            return catelog2Vos;
        }));
        String s = JSON.toJSONString(data);
        redisTemplate.opsForValue().set("catalogJson", s);
        return data;
    }

    /**
     * 本地锁
     * @return
     */
    public Map<String,List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        synchronized (this) {
            return getDataFromDb();
        }

    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }

}